//
//  HMSubmitOrderViewController.m
//  HMMarket
//
//  Created by maimaigo3 on 2017/5/11.
//  Copyright © 2017年 homai. All rights reserved.
//

#import "HMSubmitOrderViewController.h"
#import "HMCustomCartTableViewCell.h"
#import "HMDefaultAddressTableViewCell.h"
#import "HMAddressModel.h"
#import "CartModel.h"
#import "HMSelectAddressView.h"
#import "HMPayOrderViewController.h"
#import "HMMessageTableViewCell.h"
#import "HMSettingAddressController.h"
#import "HMCustomAlertView.h"
#import "HMCheapTableViewCell.h"
#import "HMSelectCheapViewController.h"

#import "CouponModel.h"


@interface HMSubmitOrderViewController ()<UITableViewDelegate, UITableViewDataSource, HMSelectAddressViewDelegate, HMCustomAlertViewDelegate, HMSettingAddressControllerDelegate>

NS_STRONG UITableView *myTableView;

NS_STRONG HMSelectAddressView *addressView;

NS_STRONG HMAddressModel *addressModel;
@property (weak, nonatomic) IBOutlet UIButton *submitBtn;
@property (weak, nonatomic) IBOutlet UILabel *totalPriceLabel;
@property (weak, nonatomic) IBOutlet UILabel *cheapPrice;

NS_STRONG NSArray *allAddressArray;

NS_COPY   NSString *message;

NS_ASSIGN float countTotalPrice;

NS_STRONG HMCustomAlertView *addressVC;

NS_STRONG HMCustomAlertView *auditVC;
NS_STRONG CouponDetail *detail;
NS_STRONG NSMutableArray *couponArray;
NS_ASSIGN float stayPrice;
@end

@implementation HMSubmitOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"确认订单";
    [self countAndGetTotalPrice];
    [self getAddressData];
    [self getCheap];
}

- (void)setUpSubview {
    _myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, KWidthSCREEN, KHeightSCREEN - 48 - 64) style:UITableViewStyleGrouped];
    _myTableView.delegate = self;
    _myTableView.dataSource = self;
    _myTableView.separatorColor = KLineColor;
    [self.view addSubview:_myTableView];
    
    [_submitBtn setBackgroundColor:kMainColor];
    [_submitBtn addTarget:self action:@selector(submitOrder) forControlEvents:UIControlEventTouchUpInside];
//    _totalPriceLabel.textColor = kPriceTextColor;
}

- (void)getCheap {
    DefaultWeakSelf;
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    [param setObjOrNil:[MGAccountTool getUid] forKey:@"uid"];
    [param setObjOrNil:@(_countTotalPrice) forKey:@"order_price"];
    
    [HttpBaseTool get:KCouponPrice params:param success:^(id responseObj) {
        self.couponArray = [CouponDetail mj_objectArrayWithKeyValuesArray:responseObj[@"data"]];
//        self.couponArray = model.list;
        if (self.couponArray.count > 0) {
            _detail = [self.couponArray firstObject];
            _countTotalPrice = _countTotalPrice - [_detail.price floatValue];
            if (_countTotalPrice < 0) {
                _countTotalPrice = 0.f;
                _totalPriceLabel.text = [NSString stringWithFormat:@"合计：¥%.2f", _countTotalPrice];
                _cheapPrice.text = [NSString stringWithFormat:@"已优惠：¥%.2f", _stayPrice];
                [weakSelf.myTableView reloadSections:[NSIndexSet indexSetWithIndex:3] withRowAnimation:UITableViewRowAnimationNone];
            } else {
                _totalPriceLabel.text = [NSString stringWithFormat:@"合计：¥%.2f", _countTotalPrice];
                _cheapPrice.text = [NSString stringWithFormat:@"已优惠：¥%.2f", [[HMReductionData replaceNullValue:_detail.price] floatValue]];
                [weakSelf.myTableView reloadSections:[NSIndexSet indexSetWithIndex:3] withRowAnimation:UITableViewRowAnimationNone];
            }
            
        } else {
            _cheapPrice.text = [NSString stringWithFormat:@"已优惠：¥%.2f", [[HMReductionData replaceNullValue:_detail.price] floatValue]];
        }
    } failure:^(NSError *error) {
        if (error.code != NSURLErrorCancelled) {
            [HMHUDManager showHUDWithText:NetWorkError];
        }
    }];
}


- (void)submitOrder {
    [self.view endEditing:YES];
    NSMutableArray *cidArray = [NSMutableArray array];
    NSString *cidString;
    
    for (int i = 0; i < _dataArray.count; i++) {
        CartModel *cartModel = _dataArray[i];
        [cidArray addObject:cartModel.cid];
        if (i == 0) {
            cidString = [NSString stringWithFormat:@"%@", cartModel.cid];
        } else {
            cidString = [NSString stringWithFormat:@"%@,%@",cidString, cartModel.cid];
        }
    }
    if (_addressModel.address.length == 0) {
        [_addressVC show];
    } else {
        NSDictionary *addOrderDict = @{@"uid":[MGAccountTool getUid], @"consignee":[HMReductionData replaceNullValue:_addressModel.consignee], @"address":[NSString stringWithFormat:@"%@%@%@%@", [HMReductionData replaceNullValue:_addressModel.province],[HMReductionData replaceNullValue:_addressModel.city],[HMReductionData replaceNullValue:_addressModel.county],[HMReductionData replaceNullValue:_addressModel.address]], @"tel":[HMReductionData replaceNullValue:_addressModel.consignee_tel], @"total_price":@(_countTotalPrice), @"comment":[HMReductionData replaceNullValue:_message], @"cid":cidString, @"coupon_id":[HMReductionData replaceNullValue:_detail.id], @"coupon_price":@([[HMReductionData replaceNullValue:_detail.price] integerValue])};
        
        [HttpBaseTool post:KAddOrder params:addOrderDict success:^(id responseObj) {
            if ([responseObj[@"code"] integerValue] == 200) {
                _refresh(@"");
                [HMHUDManager showHUDWithText:@"提交成功"];
                LoginSuccess;
                [self.navigationController popToRootViewControllerAnimated:YES];
            } else if ([responseObj[@"code"] integerValue] == 408){
                _auditVC = [[HMCustomAlertView alloc] initWithTitle:@"审核未通过，请联系客服" cancleString:@"取消" actionString:@"联系客服"];
                _auditVC.delegate = self;
                [_auditVC show];
            } else {
                [HMHUDManager showHUDWithText:responseObj[@"msg"]];
            }
        } failure:^(NSError *error) {
            
        }];
    }
}

- (void)getAddressData {
    DefaultWeakSelf;
    //默认地址
    [HttpBaseTool get:kDefalutAddress params:@{@"uid":[MGAccountTool getUid]} success:^(id responseObj) {
        if ([responseObj[@"code"] integerValue] == 200) {
            _addressModel = [[HMAddressModel mj_objectArrayWithKeyValuesArray:responseObj[@"data"]] firstObject];
            [_myTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        } else {
            NSArray *dataArray = responseObj[@"data"];
            if (dataArray.count == 0) {
                _addressVC = [[HMCustomAlertView alloc] initWithTitle:@"没有默认地址，是否填写" cancleString:@"取消" actionString:@"确认"];
                _addressVC.delegate = self;
                [_addressVC show];
            }
        }
    } failure:^(NSError *error) {
        
    }];
    
    [HttpBaseTool get:kAllAddress params:@{@"uid":[MGAccountTool getUid]} success:^(id responseObj) {
        _allAddressArray = [HMAddressModel mj_objectArrayWithKeyValuesArray:responseObj[@"data"]];
        [weakSelf setUpSubview];
    } failure:^(NSError *error) {
        
    }];
    

}



#pragma mark - HMCustomAlertViewDelegate
- (void)alert:(HMCustomAlertView *)alertView clickBnt:(select_type)clickBtn {
    if (alertView == _addressVC) {
        [_addressVC dismiss];
        DefaultWeakSelf;
        HMSettingAddressController *VC= [[HMSettingAddressController alloc] init];
//        VC.delegate = self;
        VC.refresh = ^void *(NSString *nothing) {
            [weakSelf getAddressData];
            return @"";
        };
        [self.navigationController pushViewController:VC animated:YES];
    }
    if (alertView == _auditVC) {
        NSMutableString *str = [[NSMutableString alloc] initWithFormat:@"telprompt://%@",@"4000999168"];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else if (section == 1){
        return _dataArray.count;
    } else if (section == 2){
        return 1;
    } else {
        return 1;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        HMDefaultAddressTableViewCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"HMDefaultAddressTableViewCell" owner:self options:nil] firstObject];
        cell.addressModel = _addressModel;
        return cell;
    } else if (indexPath.section == 1) {
        HMCustomCartTableViewCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"HMCustomCartTableViewCell" owner:self options:nil] firstObject];
        cell.cartModel = _dataArray[indexPath.row];
        return cell;
    } else if (indexPath.section == 2){
        HMMessageTableViewCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"HMMessageTableViewCell" owner:self options:nil] firstObject];
        cell.getMessage = ^(NSString *message) {
            _message = message;
        };
        return cell;
    } else {
        HMCheapTableViewCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"HMCheapTableViewCell" owner:self options:nil] firstObject];
//        cell.cartModel = _dataArray[indexPath.row];
        cell.ticket = _detail;
        return cell;
    }
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 105;
    } else if (indexPath.section == 1){
        return 95;
    } else if (indexPath.section == 2){
        return 85;
    } else {
        return 44;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 5;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.001;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (_allAddressArray.count == 0) {
            [_addressVC show];
        } else {
            self.addressView.dataArray = _allAddressArray;
            self.addressView.hidden = !self.addressView.hidden;
        }
    } else if (indexPath.section == 3) {
        DefaultWeakSelf;
        HMSelectCheapViewController *VC = [[HMSelectCheapViewController alloc] init];
        VC.totalPrice = _stayPrice;
        VC._detail = _detail;
        VC.getCheapTicket = ^(CouponDetail *detail) {
            [weakSelf countAndGetTotalPrice];
            
            weakSelf.detail = detail;
            
            _countTotalPrice = _countTotalPrice - [_detail.price floatValue];
            if (_countTotalPrice < 0) {
                _countTotalPrice = 0.f;
                _totalPriceLabel.text = [NSString stringWithFormat:@"合计：¥%.2f", _countTotalPrice];
                _cheapPrice.text = [NSString stringWithFormat:@"已优惠：¥%.2f", _stayPrice];
                [weakSelf.myTableView reloadSections:[NSIndexSet indexSetWithIndex:3] withRowAnimation:UITableViewRowAnimationNone];
            } else {
                _totalPriceLabel.text = [NSString stringWithFormat:@"合计：¥%.2f", _countTotalPrice];
                _cheapPrice.text = [NSString stringWithFormat:@"已优惠：¥%.2f", [[HMReductionData replaceNullValue:_detail.price] floatValue]];
                [weakSelf.myTableView reloadSections:[NSIndexSet indexSetWithIndex:3] withRowAnimation:UITableViewRowAnimationNone];
            }
           
        };
        [self.navigationController pushViewController:VC animated:YES];
    }
}

#pragma mark - HMSelectAddressViewDelegate
- (void)select:(HMAddressModel *)address {
    _addressModel = address;
    [_myTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark - HMSettingAddressControllerDelegate
- (void)refreshData {
    DefaultWeakSelf;
    [weakSelf getAddressData];
}

//计算价钱
- (void)countAndGetTotalPrice{
    _countTotalPrice = 0.f;
    for (int i = 0; i < _dataArray.count; i++) {
        CartModel *model = _dataArray[i];
        if (model.select == YES) {
            _countTotalPrice = _countTotalPrice + [model.item_price floatValue] * [model.item_number integerValue];
            MyLog(@"%.2f", _countTotalPrice);
        }
    }
    _stayPrice = _countTotalPrice;
    _totalPriceLabel.text = [NSString stringWithFormat:@"合计：¥%.2f", _countTotalPrice];
}

- (HMSelectAddressView *)addressView {
    if (_addressView == nil) {
        _addressView = [[HMSelectAddressView alloc] initWithFrame:CGRectMake(0, 64 + 115, KWidthSCREEN, KHeightSCREEN - 64 - 115)];
        _addressView.delegate = self;
    }
    return _addressView;
}



- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (_addressView != nil) {
        [_addressView dismiss];
    }
}

@end
